package com.atguigu.gulimall.order.config;


import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.fastjson.JSON;
import com.atguigu.common.exception.BizCodeEnume;
import com.atguigu.common.utils.R;
import org.springframework.context.annotation.Configuration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @ClassName SeckillSentineConfig
 * @Description 自定义sentinel异常统一返回信息
 * @Author zhonghuaen
 * @Date 2020/12/22 21:52
 * @Version 1.0
 */
@Configuration
public class SeckillSentineConfig implements BlockExceptionHandler {

    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws Exception {
        //        Result responseData = null;
        //BlockException  异常接口,包含Sentinel的五个异常
        //  FlowException  限流异常
        //  DegradeException  降级异常
        //  ParamFlowException  参数限流异常
        //  AuthorityException  授权异常
        //  SystemBlockException  系统负载异常
//        if (e instanceof FlowException) {
//            responseData = Result.getFailResult(410, "接口被限流了...");
//        } else if (e instanceof DegradeException) {
//            responseData = Result.getFailResult(420, "接口被降级了...");
//        } else if (e instanceof ParamFlowException) {
//            responseData = Result.getFailResult(430, "参数限流异常...");
//        } else if (e instanceof AuthorityException) {
//            responseData = Result.getFailResult(440, "授权异常...");
//        } else if (e instanceof SystemBlockException) {
//            responseData = Result.getFailResult(450, "系统负载异常...");
//        }

        R error = R.error(BizCodeEnume.TOO_MANY_REQUEST.getCode(), BizCodeEnume.TOO_MANY_REQUEST.getMsg());
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("application/json");
        httpServletResponse.getWriter().write(JSON.toJSONString(error));
    }
}
